package com.jgads.ad.sdk.mediation.adapter;

import android.content.Context;
import android.util.Log;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.mediation.MediationConstant;
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.native_ad.MediationCustomNativeLoader;
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig;
import com.jgads.ad.sdk.mediation.utils.ThreadUtils;
import com.junion.ad.BidLossNotice;
import com.junion.ad.NativeAd;
import com.junion.ad.NativeExpressAd;
import com.junion.ad.bean.NativeAdInfo;
import com.junion.ad.bean.NativeExpressAdInfo;
import com.junion.ad.entity.JUnionAdSize;
import com.junion.ad.error.JUnionError;
import com.junion.ad.listener.NativeAdListener;
import com.junion.ad.listener.NativeExpressAdListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: maipian
 * @CreateDate: 12/23/21 6:14 PM
 */
public class CustomerNativeAdapter extends MediationCustomNativeLoader {

    private List<JUnionNativeExpressAd> nativeExpressAds;
    private List<JUnionNativeAd> nativeAds;

    @Override
    public void load(final Context context, AdSlot adSlot, final MediationCustomServiceConfig serviceConfig) {

        ThreadUtils.runOnUIThreadByThreadPool(new Runnable() {
            @Override
            public void run() {
                if (isExpressRender()) {
                    int widthPixels = context.getResources().getDisplayMetrics().widthPixels;
                    NativeExpressAd nativeExpressAd = new NativeExpressAd(context, new JUnionAdSize(widthPixels, 0));
                    nativeExpressAd.setMute(true);
                    nativeExpressAd.setListener(new NativeExpressAdListener() {
                        @Override
                        public void onRenderFailed(NativeExpressAdInfo nativeExpressAdInfo, JUnionError error) {
                        }

                        @Override
                        public void onAdReceive(List<NativeExpressAdInfo> list) {
                            nativeExpressAds = new ArrayList<>();
                            for (NativeExpressAdInfo nativeExpressAdInfo : list) {
                                JUnionNativeExpressAd JUnionNativeExpressAd = new JUnionNativeExpressAd(nativeExpressAdInfo, getBiddingType());
                                if (isClientBidding()) {
                                    //bidding广告类型，回传竞价广告价格 单位：分
                                    JUnionNativeExpressAd.setBiddingPrice(nativeExpressAdInfo.getBidPrice());
                                }
                                nativeExpressAds.add(JUnionNativeExpressAd);
                            }
                            callLoadSuccess(nativeExpressAds);
                        }

                        @Override
                        public void onAdExpose(NativeExpressAdInfo adInfo) {
                            getJUnionNativeExpressAd(adInfo).callAdShow();
                        }

                        @Override
                        public void onAdClick(NativeExpressAdInfo adInfo) {
                            getJUnionNativeExpressAd(adInfo).callAdClick();
                        }

                        @Override
                        public void onAdClose(NativeExpressAdInfo adInfo) {
                            getJUnionNativeExpressAd(adInfo).clear();
                        }

                        @Override
                        public void onAdFailed(JUnionError JUnionError) {
                            callLoadFail(JUnionError.getCode(), JUnionError.getError());
                        }
                    });

                    if (serviceConfig != null) {
                        nativeExpressAd.loadAd(serviceConfig.getADNNetworkSlotId());
                    }
                } else if (isNativeAd()) {
                    NativeAd nativeAd = new NativeAd(context);
                    nativeAd.setMute(true);
                    nativeAd.setListener(new NativeAdListener() {
                        @Override
                        public void onRenderFailed(NativeAdInfo nativeExpressAdInfo, JUnionError error) {
                        }

                        @Override
                        public void onAdReceive(List<NativeAdInfo> list) {
                            nativeAds = new ArrayList<>();
                            for (NativeAdInfo nativeAdInfo : list) {
                                JUnionNativeAd JUnionNativeAd = new JUnionNativeAd(nativeAdInfo, getBiddingType());
                                nativeAds.add(JUnionNativeAd);
                                if (isClientBidding()) {
                                    //bidding广告类型，回传竞价广告价格 单位：分
                                    JUnionNativeAd.setBiddingPrice(nativeAdInfo.getBidPrice());
                                }

                            }
                            callLoadSuccess(nativeAds);
                        }

                        @Override
                        public void onAdExpose(NativeAdInfo adInfo) {
                            getJUnionNativeAd(adInfo).callAdShow();
                        }

                        @Override
                        public void onAdClick(NativeAdInfo adInfo) {
                            getJUnionNativeAd(adInfo).callAdClick();
                        }

                        @Override
                        public void onAdClose(NativeAdInfo adInfo) {
                            getJUnionNativeAd(adInfo).callDislikeSelected(0, "关闭");
                        }

                        @Override
                        public void onAdFailed(JUnionError JUnionError) {
                            callLoadFail(JUnionError.getCode(), JUnionError.getError());
                        }
                    });

                    if (serviceConfig != null) {
                        nativeAd.loadAd(serviceConfig.getADNNetworkSlotId());
                    }
                }
            }
        });
    }

    private JUnionNativeExpressAd getJUnionNativeExpressAd(NativeExpressAdInfo adInfo) {
        for (int i = 0; i < nativeExpressAds.size(); i++) {
            if (nativeExpressAds.get(i).getNativeExpressAdInfo() == adInfo) {
                return nativeExpressAds.get(i);
            }
        }
        return null;
    }

    private JUnionNativeAd getJUnionNativeAd(NativeAdInfo adInfo) {
        for (int i = 0; i < nativeAds.size(); i++) {
            if (nativeAds.get(i).getNativeAdInfo() == adInfo) {
                return nativeAds.get(i);
            }
        }
        return null;
    }

    /**
     * 是否clientBidding广告
     *
     * @return
     */
    public boolean isClientBidding() {
        return getBiddingType() == MediationConstant.AD_TYPE_CLIENT_BIDING;
    }

    /**
     * @param win         是否在本次竞价中获胜
     * @param winnerPrice 获胜者价格，可能为0 ,如果没有胜出则该值是-1
     * @param loseReason  竞价失败原因 1:价格较低 2：广告返回超时 10001：其他；如果胜出则该值是-1
     * @param extra       扩展参数
     */
    @Override
    public void receiveBidResult(boolean win, double winnerPrice, int loseReason, Map<String, Object> extra) {
        Log.d(Const.TAG, "receiveBidResult   win = "+ win+"  "+
                "winnerPrice = "+winnerPrice +"  "+
                "loseReason = " +loseReason  +"  "+
                Thread.currentThread().toString());
        if (win) {
            //竞价成功
            if (isExpressRender()) {
                if (nativeExpressAds != null && nativeExpressAds.size() > 0) {
                    for (JUnionNativeExpressAd JUnionNativeExpressAd : nativeExpressAds) {
                        NativeExpressAdInfo JUnionExpressAdInfo = JUnionNativeExpressAd.getNativeExpressAdInfo();
                        if (JUnionExpressAdInfo != null && !JUnionExpressAdInfo.isReportBidWin()) {
                            JUnionExpressAdInfo.sendWinNotice((int) winnerPrice);
                        }
                    }
                }
            } else {
                if (nativeAds != null && nativeAds.size() > 0) {
                    for (JUnionNativeAd JUnionNativeAd : nativeAds) {
                        NativeAdInfo JUnionNativeAdInfo = JUnionNativeAd.getNativeAdInfo();
                        if (JUnionNativeAdInfo != null && !JUnionNativeAdInfo.isReportBidWin()) {
                            JUnionNativeAdInfo.sendWinNotice((int) winnerPrice);
                        }
                    }
                }

            }

        } else {
            //竞价失败
            if (isExpressRender()) {
                if (nativeExpressAds != null && nativeExpressAds.size() > 0) {
                    for (JUnionNativeExpressAd JUnionNativeExpressAd : nativeExpressAds) {
                        NativeExpressAdInfo JUnionExpressAdInfo = JUnionNativeExpressAd.getNativeExpressAdInfo();
                        if (JUnionExpressAdInfo != null) {
                            if (loseReason == 1) {
                                JUnionExpressAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.LOW_PRICE);
                            } else {
                                JUnionExpressAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.OTHER);
                            }
                        }
                    }
                }
            } else {
                if (nativeAds != null && nativeAds.size() > 0) {
                    for (JUnionNativeAd JUnionNativeAd : nativeAds) {
                        NativeAdInfo JUnionNativeAdInfo = JUnionNativeAd.getNativeAdInfo();
                        if (JUnionNativeAdInfo != null) {
                            if (JUnionNativeAdInfo != null) {
                                if (loseReason == 1) {
                                    JUnionNativeAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.LOW_PRICE);
                                } else {
                                    JUnionNativeAdInfo.sendLossNotice((int) winnerPrice, BidLossNotice.OTHER);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

}
